package com.vonchange.purchase.web;


import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.vonchange.headb.core.map.HeaMap;
import com.vonchange.purchase.good.bean.Good;
import com.vonchange.purchase.good.service.IGoodService;
import com.vonchange.purchase.merchant.bean.Merchant;
import com.vonchange.purchase.merchant.service.IMerchantService;
import com.vonchange.purchase.purchase.bean.Purchase;
import com.vonchange.purchase.purchase.service.IPurchaseService;

@Controller
@RequestMapping("/web")
public class WebAction {
	@Resource
	private IGoodService goodService;
	@Resource
	private IMerchantService merchantService;
	@Resource
	private IPurchaseService purchaseService;
	@RequestMapping("/goodEntry/{deedId}")
	public ModelAndView good_entry_main(@PathVariable("deedId")String deedId,ModelAndView mav){
		Merchant merchant=    merchantService.findFirst(new HeaMap().set("parentId_eq", 0));
		mav.setViewName("redirect:"+deedId+"/"+merchant.getId());
		return mav;
	}
	@RequestMapping("/goodEntry/{deedId}/{merchantId}")
	public ModelAndView good_entry(@PathVariable("deedId")String deedId,@PathVariable("merchantId")String merchantId,ModelAndView mav){
		List<Good> goodList=goodService.findList(null);
	    List<Merchant> merchantList=	merchantService.findList(new HeaMap().set("parentId_eq", 0));
	    List<Merchant> subList=null;
	    for (Merchant merchant : merchantList) {
	    	 subList=merchantService.findList(new HeaMap().set("parentId_eq",merchant.getId()));
	    	 merchant.setSubMerchants(subList);
		}
	    Merchant merchant=    merchantService.findById(merchantId);
	    Merchant parentMerchant=    null;
	    if(!"0".equals(merchant.getParentId())){
	    	parentMerchant=    merchantService.findById(merchant.getParentId());
	    }
		long num=merchantService.count(new HeaMap().set("parentId_eq", merchant.getId()));
		if(num>0){
			merchant.setHasChild(true);
		}
	    List<Purchase> purchaseList=   purchaseService.findList(new HeaMap().set("deedId_eq", deedId).set("merchantId_eq", merchantId));
		mav.addObject("goodList", goodList);
		mav.addObject("deedId", deedId);
		mav.addObject("merchantList", merchantList);
		mav.addObject("merchant", merchant);
		mav.addObject("parentMerchant", parentMerchant);
		mav.addObject("merchantId", merchantId);
		mav.addObject("purchaseList", purchaseList);
		mav.setViewName("main/good_entry");
		return mav;
	}
	@RequestMapping("/test")
	public ModelAndView test(ModelAndView mav){
		mav.setViewName("main/test");
		return mav;
	}
	@RequestMapping("/deedList")
	public ModelAndView deedList(ModelAndView mav){

		mav.setViewName("main/deed_list");
		return mav;
	}
}
